/**
 * @author Hemant
 * Field.java
 * This class represents a Field object.It handles request for field object.
 */


/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  guiproperty;

import java.io.RandomAccessFile;
import java.util.Hashtable;
import java.util.LinkedList;

import dbmanager.DBManager;
import dbmanager.GetIdName;

import utility.CapitalChar;
import utility.Input;

public class Field implements HTMLInterface
{
	String tag="",line="",header="",report,displaytext="",ObjectName,param = "",text,select,noselect,alias;
	RandomAccessFile raf;
	StringBuffer buffer;
	boolean end;
	private LinkedList<Object> PropList;
	Hashtable<Object, Object> hash;
	private Hashtable<Object, LinkedList<Object>> ObjProp ;
	GetIdName get;
	public static HTMLInterface obj;
	public static String original_text;
	/**
	 * This method sets object name for the object name contained in hashtable.
	 * @param Objectname Object name of Field object.
	 */
	public void setObjectName(String ObjectName) 
	{
		this.ObjectName = ObjectName;		
	}
	
	/**
	 * This method accepts Hashtable containing tag objects and its properties.
	 * It extracts the object specific property list.
	 * @param ObjectPropertyList hashtable containing objects and its properties.
	 */	
	public void setObjPropertyList(Hashtable<Object, LinkedList<Object>> ObjectPropertyList) 
	{
		this.ObjProp = ObjectPropertyList;
		this.PropList = ObjectPropertyList.get(this.ObjectName);
	}
	
	/**
	 * This method sets the tag to be used in HTML code. 
	 * @param tag HTML tag.
	 */
	public void setTag(String tag)
	{
		this.tag = tag;
	}
		
	/**
	 * This method sets report name.
	 * @param report Report.
	 */
	public void setReport(String report) 
	{
		this.report = report;
	}
	
	/**
	 * This method sets line of file to be processed.
	 * @param line Data line.
	 */
	public void setLine(String line) 
	{
		this.line = line;
	}
	
	/**
	 * This method sets the parameter for web report
	 * @param param 
	 */	
	public void setParam(String param) 
	{
		this.param = param;
    }
	
	/**
	 * This method sets GetIdName class object.
	 * @param GetIdName object 
	 */
	public void setGetIdName(GetIdName get) 
	{
		this.get = get;
	}
	
	public void isEnd(boolean end)
	{
		this.end = end;
	}
	
	/**
	 * It generates HTML string for specific object using its property list 
	 * @return String of HTML tags for that specific tag object 
	 */
	public String getHTMLCode()
	{
		try {
			// set size of list to a variable
			int size = PropList.size();
			
			buffer = new StringBuffer("");
			StringBuffer tempbuffer = new StringBuffer("");
			
			HTMLInterface tagobj = null;
			String classvar = "";
			// iterate over list
			
			for(int i = 0;i < size;i++ )
			{
				String [] property = PropList.get(i).toString().split("\t");
				System.out.println("The property array is "+PropList.get(i));
				
				// set text property value to text
				if(property[0].equalsIgnoreCase("text"))
				{
			         text = property[1];        
				}
				else if(property[0].equalsIgnoreCase("alias"))
				{
			        alias = property[1];        
				}
				//set type proerty value to tag
				else if(property[0].equalsIgnoreCase("type"))
				{
					tag = property[1];
				}			
				// craete a class object for the property
				else
				{
					// create classname variable using property
					String classname = CapitalChar.makeFirstCharCapital(property[0]);
					classvar = property[1];
					
					try
					{
						// load property class and set it to a Class variable
						Class<Object> c = (Class<Object>)Class.forName("guiproperty."+classname);
						
						try
						{
							//create instance of property class
							tagobj = (HTMLInterface)c.newInstance();
						}
						catch (InstantiationException e) 
						{
							e.printStackTrace();
						} 
						catch (IllegalAccessException e) 
						{
							e.printStackTrace();
						}
					}
					catch (ClassNotFoundException e) 
					{
						tagobj = null;
						e.printStackTrace();
					}			
				}
			}
			
				       	
			 try
			 {
			 	// extract heading from text file then split headings into an array
			 	// so that those headings are used as index for data below it
					
				System.out.println("The dataline is ---"+line);
				String headingArr [] = null;
				// split data line 
				String arr [] = null;
				
				try
				{
					headingArr = header.split(Input.SEPARATOR);
					arr = line.split(String.valueOf(Input.SEPARATOR));
				}
				catch(ArrayIndexOutOfBoundsException e)
				{
					headingArr[0] = header;
					arr[0] = line;
				}
					
				// iterate over heading list. if heading matches to text property value
				// the set that data as text
				// if there is another tag in side field object then pass on all data to 
				// next tag object 
				// else append that text to buffer
				
				boolean setEnd = false;
				boolean isAll = false;
					
				for(int j = 0;j < headingArr.length;j++)
				{
					System.out.println("The heading id "+headingArr[j]);
					
					try
					{
						if(text.equalsIgnoreCase("*"))
							isAll = true;
					}
					catch(NullPointerException e)
					{
						isAll = false;
					}
					
					int start_loc = text.indexOf("$");
					int end_loc = text.lastIndexOf("$");
					
					if(text.startsWith("$") && text.endsWith("$") && (start_loc != end_loc))
					{
						text = text.substring(1, text.length()-1);
					}
					if(headingArr[j].equalsIgnoreCase(text) || isAll)
					{
						// get value for field defined in "text" from hash						
						try
						{
							this.param = (String)hash.get(text.toLowerCase());
							
							if(param == null)
								param = (String)hash.get(alias);						
						}
						catch (NullPointerException e) 
						{
							//e.printStackTrace();
						}
						
						text = arr[j];
						original_text = text;
						// since property val of select or noselect is an Select object
						// we can directly use Select object 
						//obj = new Select();
						obj = new Tag();
						// if the text is what we have to highlight
						if(text.equalsIgnoreCase(param))
						{
							//Vertical.selected  = true;
							obj.setObjectName(select);
						}
						else
						{
							obj.setObjectName(noselect);						
						}
						
						obj.setObjPropertyList(ObjProp);
						obj.setGetIdName(get);
						obj.setText(buffer.toString());
						obj.setLine(line);		
						obj.setHeaderLine(header);
						obj.setParam(param);
						obj.setReport(report);
						//obj.setTag(tag);
						obj.setParamHash(hash);
						
						if(tagobj != null)
						{
							// Lets first get the output of internal tag object and pass it to select object 
							tagobj.setGetIdName(get);
							tagobj.setText(CapitalChar.makeFirstCharCapital(text));
							tagobj.setLine(line);
							tagobj.setHeaderLine(header);
							tagobj.setObjectName(classvar);
							tagobj.setObjPropertyList(ObjProp);
							tagobj.setParam(param);
							tagobj.setReport(report);
							tagobj.setParamHash(hash);
							//tagobj.setTag(tag);
							text = tagobj.getHTMLCode();
						}
						else
							text = CapitalChar.makeFirstCharCapital(text);
						
						obj.setText(text);
						tempbuffer.append(text);
												
						if(Vertical.selected==false && end==true)
						{
							setEnd = true;
						}
						
						if(!isAll)
							break;
					}
				}
			 }
			 catch (Exception e) 
			 {
				 e.printStackTrace();
			 }
			                
			System.out.println("The buffer in Field class is "+tempbuffer.toString());
			return tempbuffer.toString();
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * @param text Text to be displayed.
	 */
	public void setText(String text) 
	{
		this.text = text;
	}

	public void setParamHash(Hashtable<Object, Object> hash) {
		this.hash = hash;
	}

	public void setNoSelectObject(String select) {
		this.noselect = select;
	}

	public void setSelectObject(String select) {
		this.select = select;
	}

	public void setHeaderLine(String header) {
		// TODO Auto-generated method stub
		this.header = header;
	}			
}